package com.yulongtian.offers.day202212;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/find-pivot-index/?envType=study-plan&id=leetcode_75_level_1&plan=leetcode_75&plan_progress=y7sk2g7
 *
 * @author yulongTian
 * @create 2022-12-13 11:32
 */
public class Test02 {
    public static void main(String[] args) {
        System.out.println(pivotIndex(new int[]{-1,-1,1,1,0,0}));
    }

    public static int pivotIndex(int[] nums) {
        int len = nums.length;
        if (len == 1) {
            return 0;
        }
        int[] leftSum = new int[len];
        int[] rightSum = new int[len];
        leftSum[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            leftSum[i] = leftSum[i - 1] + nums[i];
        }

        rightSum[len - 1] = nums[len - 1];
        for (int i = len - 2; i >= 0; i--) {
            rightSum[i] = rightSum[i + 1] + nums[i];
        }

        //检查两端
        if (rightSum[1] == 0) {
            return 0;
        }


        for (int i = 0; i < len - 2; i++) {
            if (leftSum[i] == rightSum[i + 2]) {
                return i + 1;
            }
        }
         if (leftSum[len - 2] == 0) {
            return len - 1;
        }




        return -1;
    }

}
